<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/20
 * Time: 0:06
 */

namespace sdk;

// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;

class Upload
{
    // 七牛SDK
    private $accessKey;
    private $secretKey;
    private $bucket;
    private $auth;
    private $token;

    /**
     * 初始化
     * @param string $bucket 七牛云空间
     * @param string $accessKey 七牛云accessKey
     * @param string $secretKey 七牛云secretKey
     */
    public function __construct($bucket = null, $accessKey = null, $secretKey = null)
    {
        $this->bucket = empty($bucket) ? config('qiniu.bucket') : $bucket;
        $this->accessKey = empty($accessKey) ? config('qiniu.accessKey') : $accessKey;
        $this->secretKey = empty($secretKey) ? config('qiniu.secretKey') : $secretKey;
        // 构建鉴权对象
        $this->auth = new Auth($this->accessKey, $this->secretKey);
        // 生成上传 Token
        $this->token = $this->auth->uploadToken($this->bucket);
    }

    public function image($info)
    {


        // 要上传文件的本地路径
        $file = $info['tmp_name'];

        // 需要保存的文件后缀名
        $suffix = pathinfo($info['name']);
        $exten = $suffix['extension'];

        // 上传到七牛后保存的文件名
        $key = date('Y').'/'.date('m').'/'.substr(md5($file),0,5).date('YmdHis').mt_rand(1000,9999).'.'.$exten;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($this->token, $key, $file);

        if ($err !== null) {
            return null;
        } else {
            return $key;
        }

    }
}